<?php

class Owner extends BaseOwner {
	private $token = null;
	private $validated = null;

	public function setToken($token) {
		$this->token = $token;
	}

	public function isYubiValid() {
		if($this->validated===null)
			$this->validated = KeyGenius::validateToken($this->token);
		if($this->validated and $this->isNew()) $this->save();
		return $this->validated;
	}

	public function getPasswordForDomain($domain) {
		if(!$this->isNew()) {
			$pw = $this->lookupPasswordForDomain($domain);
			if($pw!=null and $this->isYubiValid()) {
				$pw->setToken($this->token);
				return $pw->value;
			}
		}
		return null;
	}

	public function setPasswordForDomain($domain, $value=null) {
		if(!$this->isYubiValid()) return null;
		$pw_table = Doctrine::getTable('Password');
		if($value===null) {
			$pw_table->deleteOneByOwnerAndDomain($this, $domain);
		} else {
			$pw = $pw_table->findOrCreateOneByOwnerAndDomain($this, $domain);
			$pw->setToken($this->token);
			$pw->value = $value;
			$pw->save();
		}
		return $value;
	}

	public function generateRevocationCode() {
		if(!$this->isYubiValid()) return null;
		$code = hash(sfConfig::get('app_crypto_hash'), $this->token.mt_rand());
		$this->revocation = hash(sfConfig::get('app_crypto_hash'), $code);
		$this->save();
		return $code;
	}

	private function lookupPasswordForDomain($domain) {
		$pos = strpos($domain, '.');
		if($pos===false) return null;
		$pw = Doctrine::getTable('Password')->findOneByOwnerAndDomain($this, $domain);
		return $pw ? $pw : $this->lookupPasswordForDomain(substr($domain, $pos+1));
	}
}
